package com.wangsd.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * MD5加密工具类
 */
@Slf4j
public class MD5Utils {

    public static String getMD5Sign(Map<String, String> map, String key, int type) {
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, String>> entry = map.entrySet();
        String signStr = null;
        if (type == 1) { /** 签名串 a=1&b=2&key=abc (小写)*/
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getKey() + "=" + temp.getValue() + "&");
            }
            sb.append("key=" + key);
            signStr = DigestUtils.md5Hex(sb.toString()).toLowerCase();
        } else if (type == 2) { /** 签名串 a=1&b=2&key=abc (大写)*/
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getKey() + "=" + temp.getValue() + "&");
            }
            sb.append("key=" + key);
            signStr = DigestUtils.md5Hex(sb.toString()).toUpperCase();
        } else if (type == 3) { /** 签名串 a=1&b=2abc (小写)*/
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getKey() + "=" + temp.getValue() + "&");
            }
            sb = sb.replace(sb.length() - 1, sb.length(), "");
            sb.append(key);
            signStr = DigestUtils.md5Hex(sb.toString()).toLowerCase();
        } else if (type == 4) { /** 签名串 a=1&b=2&abc (大写)*/
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getKey() + "=" + temp.getValue() + "&");
            }
            sb.append(key);
            signStr = DigestUtils.md5Hex(sb.toString()).toUpperCase();
        } else if (type == 5) { /** 签名串 a=1|b=2|abc (大写)*/
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getValue() + "|");
            }
            sb.append(key);
            signStr = DigestUtils.md5Hex(sb.toString()).toUpperCase();
        }
        log.debug("签名串：" + sb.toString() + " 签名结果：" + signStr);
        return signStr;
    }

    /**
     * 发放商家券时获取sign
     * @param map
     * @param key
     * @return
     */
    public static String getSignCoupon(Map map, String key) {
        try {
            StringBuffer sb = new StringBuffer();
            Set<Map.Entry<String, String>> entry = map.entrySet();
            for (Map.Entry<String, String> temp : entry) {
                sb.append(temp.getKey() + "=" + temp.getValue() + "&");
            }
            sb.append("key=" + key);
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] array = sha256_HMAC.doFinal(sb.toString().getBytes("UTF-8"));
            StringBuilder result = new StringBuilder();
            for (byte item : array) {
                result.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }
            String signStr = result.toString().toUpperCase();
            log.debug("发放商家券时获取sign==" + signStr);
            return signStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String outNO = System.currentTimeMillis() + "";
        SortedMap<String, String> map = new TreeMap();
        map.put("out_request_no0", outNO);
        map.put("send_coupon_merchant", "1534072691");
        map.put("stock_id0", "1218400000000023");
        log.debug(outNO);
        MD5Utils.getSignCoupon(map, "047oaGf9ZGdTMumCoBHOt7AdInFTnxSu");
    }
}
